 //
//  FindCarViewController.m
//  CarHome
//
//  Created by 王建男 on 14-9-17.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "FindCarViewController.h"
#import "SellTableViewCell.h"
#import "CardetailsModel.h"
#import "FindCarModel.h"
#import "CarModel_table.h"
#import "CarModel_Tableview.h"
#import "ShowView.h"
#import "DetailedViewController.h"
#import "ChooseCarVIew.h"

@interface FindCarViewController ()

@end

NSString *const TableViewCellIdentifier = @"Cell_FindCar";

@implementation FindCarViewController

- (void)dealloc
{
    [_tableView release];
    [_tableView_Array release];
    [_allCar release];
    [_urlStr release];
    [_urlStr_bid release];
    
    _tableView = nil;
    _tableView_Array = nil;
    _allCar = nil;
    _urlStr = nil;
    _urlStr_bid = nil;
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _tableView_Array = [[NSMutableArray alloc] init];
        
       self.urlStr =  [[NSMutableString alloc] initWithFormat:@"%@", noMark]; //存储网络连接用于加载
        _urlStr_bid = [[NSMutableString alloc] initWithString:@"0"];
        [_urlStr release];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationController.navigationBar.barTintColor = myColor_dark;
    self.navigationController.navigationBar.barTintColor = myColor_dark;
    self.tabBarController.tabBar.barTintColor = myColor_dark;//tabBar颜色

    // nav的标题
    [self.navigationItem setTitle:@"精选车库"];
    NSDictionary * dic=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:20], NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:dic];
    
    [self connect:noMark];
    [self creatTableView];
    [self creatButton];
}

#pragma mark -
#pragma mark creatButton
- (void)creatButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 70, 40)];
    
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, 18, 0, -18)];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 18, 0, -18)];
    
    [button setTitle:@"品牌" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"DrawerButton.png"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(showRight:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:button]];
    [button release];
}

- (void)showRight:(id)sender
{
    
    ChooseCarVIew *chooseView = [[ChooseCarVIew alloc] initWithFrame:CGRectMake(0, 0, self.tabBarController.view.frame.size.width, self.tabBarController.view.frame.size.height)];
    [chooseView showBlock:^(NSString *carId) {
        
        [_urlStr release];
        _urlStr =  [[NSMutableString alloc] initWithFormat:@"%@", noMark];
        
        NSRange subStr = [_urlStr rangeOfString:[NSString stringWithFormat:@"bid%@", _urlStr_bid]];
    
        if (subStr.location != NSNotFound) {
            [_urlStr replaceCharactersInRange:subStr withString:[NSString stringWithFormat:@"bid%@", carId]];
        }
        [_pagecount release];
        [_tableView_Array removeAllObjects];
        
        [self connect:_urlStr];
        [chooseView removeFromSuperview];
        
        [_tableView setContentOffset:CGPointMake(0, 0) animated:NO];
        
    }];
    [self.tabBarController.view addSubview:chooseView];
    [chooseView release];
}

static int a = 1;

#pragma mark -
#pragma mark 网络请求

- (void)connect:(NSString *)url
{
    [NetUrl connect:url parmater:nil Block:^(NSData *data) {
        
        NSDictionary *car_Dictionary = (NSDictionary *)data;
        
        _pagecount = [[NSString alloc] initWithFormat:@"%@", [[car_Dictionary objectForKey:@"result"]objectForKey:@"pagecount"]];
        
        _allCar = [[FindCarModel alloc] init];
        _allCar.car_Count = [[[car_Dictionary objectForKey:@"result"] objectForKey:@"seriesitems"] count];
        _allCar.rowcount = [[car_Dictionary objectForKey:@"result"] objectForKey:@"rowcount"];
        _allCar.tobalspeccount = [[car_Dictionary objectForKey:@"result"] objectForKey:@"tobalspeccount"];
        _allCar.seriesitems = [[car_Dictionary objectForKey:@"result"] objectForKey:@"seriesitems"];
        
        for (NSMutableDictionary *dic in _allCar.seriesitems) {
            CardetailsModel *model = [[CardetailsModel alloc] init];
            model.id = [dic objectForKey:@"id"];
            model.name = [dic objectForKey:@"name"];
            model.img = [dic objectForKey:@"img"];
            model.level = [dic objectForKey:@"level"];
            model.price = [dic objectForKey:@"price"];
            model.count = [[dic objectForKey:@"count"] intValue];
            model.spcitemgroups = [dic objectForKey:@"specitemgroups"];
            
            [_tableView_Array addObject:model];
            [model release];
        }
        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
        [_tableView reloadData];
    }];
}

#pragma mark -
#pragma mark creatTableView

- (void)creatTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[SellTableViewCell class] forCellReuseIdentifier:TableViewCellIdentifier];
    
    [self.view addSubview:_tableView];
    
    [self setupRefresh];
    }

#pragma mark -
#pragma mark TableView协议

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableView_Array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier forIndexPath:indexPath];
    if ([_tableView_Array count] != 0) {
        CardetailsModel *model = [_tableView_Array objectAtIndex:indexPath.row];
        
        [cell setCell:model.img Andname:model.name Andmodel:model.level Andprice:model.price];
    }
   
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //cell动画
    if ([_tableView_Array count] != 0) {
        cell.frame = CGRectMake(-cell.frame.size.width, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        [UIView animateWithDuration:0.5 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        }];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    //车型
    
    ShowView *showView = [[ShowView alloc] initWithFrame:CGRectMake(0, 0, self.tabBarController.view.frame.size.width, self.tabBarController.view.frame.size.height)];
    
    CardetailsModel *models = [_tableView_Array objectAtIndex:indexPath.row];
    NSMutableArray *array = [[NSMutableArray alloc] init];
    
    //传入数据
    for (NSMutableDictionary *dic in models.spcitemgroups) {
        CarModel_table *carTable = [[CarModel_table alloc] init];
        [carTable setValues:dic];
        [array addObject:carTable];
    }
    CardetailsModel *details = [_tableView_Array objectAtIndex:indexPath.row];
    
   [showView setName:array AndSpeciteId:details.id];
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [showView showBlock:^(NSString *carId, NSString *carName) {
        DetailedViewController *detailed =
        [[DetailedViewController alloc] init];
        
        [detailed setConnect:carId AndSpe:details.id Andtitle:carName];
        
        [self presentViewController:detailed animated:YES completion:^{
        }];
        [detailed release];
    }];
    [self.tabBarController.view addSubview:showView];
   
    [showView release];
    [array release];
}

#pragma mark -
#pragma mark 隐藏tabBar

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    [self.tabBarController.tabBar setHidden:NO];
}

#pragma mark -
#pragma mark setRefresh上拉加载 下拉刷新

- (void)setupRefresh
{
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    _tableView.headerPullToRefreshText = @"下拉刷新";
    _tableView.headerReleaseToRefreshText = @"释放刷新";
    _tableView.headerRefreshingText = @"正在刷新中···";
    _tableView.footerPullToRefreshText = @"上拉加载";
    _tableView.footerReleaseToRefreshText = @"释放加载";
    _tableView.footerRefreshingText = @"正在加载中···";
}

- (void)headerRereshing
{
    [_tableView_Array removeAllObjects];
    [_pagecount release];
    [self connect:noMark];
    [_urlStr release];
    _urlStr =  [[NSMutableString alloc] initWithFormat:@"%@", noMark];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_tableView reloadData];
        a = 1;
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
    });
}


- (void)footerRereshing
{
    // 加载网址拼接
    if ([_pagecount intValue] >= a) {
        _tableView.footerRefreshingText = @"加载中";
        NSRange subStr = [_urlStr rangeOfString:[NSString stringWithFormat:@"p%d", a]];
        a++;
        if (subStr.location != NSNotFound) {
            [_urlStr replaceCharactersInRange:subStr withString:[NSString stringWithFormat:@"p%d", a]];
        }
        [_pagecount release];
        [self connect:_urlStr];
        
    } else {
        _tableView.footerRefreshingText = @"已经最低了";
         [_tableView footerEndRefreshing];
    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
